package main

import (
	"github.com/kingwrcy/devNews/provider"
	"github.com/kingwrcy/devNews/web"
	"log"
	"os"
	"time"
)

func doOnce(news []provider.NewsProvider, storage provider.Storage) {
	for _, p := range news {
		news := p.GetData(time.Now())
		storage.Save(p.Name(), news)
	}
}

func main() {

	logfile, err := os.Create("devNews.log")

	if err != nil {
		log.Fatal("cat not open devNews.log file,", err)
	}

	log.SetOutput(logfile)
	log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)

	defer logfile.Close()

	newsProviders := []provider.NewsProvider{
		&provider.JueJinProvider{},
		&provider.MaNongProvider{},
		&provider.TouTiaoProvider{},
	}

	//storage := provider.NewRedisStorage("127.0.0.1:6379")
	//storage := provider.NewRedisStorage("127.0.0.1:6379")
	storage := provider.NewMongoStorage("127.0.0.1:27017")
	defer storage.Close()

	for _, p := range newsProviders {
		tt := time.NewTicker(p.Schedule())
		go func(t *time.Ticker, p provider.NewsProvider) {
			for _ = range t.C {
				news := p.GetData(time.Now())
				storage.Save(p.Name(), news)
			}
		}(tt, p)
	}

	go doOnce(newsProviders, storage)

	web.StartServer(storage)

}
